﻿ using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WMM.Tapioca.Instance;
using WMM.Tapioca.Taxonomy;
using WMM.Tapioca.Linkbase;
using System.Xml.Linq;
using WMM.Tapioca.Utilities;

namespace WMM.Tapioca.Formula.Filters
{
    /// <summary>
    /// The relative filter can be used to select facts for which the aspects that are covered by
    /// the relative filter, have values that match the corresponding aspects of another fact.
    /// </summary>
    public class RelativeFilter : Filter
    {
        private string variable;

        /// <returns> Source variable. </returns>
        public string Variable
        {
            get { return variable; }
            set { variable = value; }
        }

        /// <summary>
        /// Constructor.
        /// </summary>
        public RelativeFilter(Resource resource)
            : base(resource)
        {
            variable = (string)resource.ResourceXElement.Attribute("variable") ?? string.Empty;
        }


        public override List<FactItem> EvaluateFilter(VariableSet variableSet, List<FactItem> itemsToFilter, DTS dts)
        {
            List<FactItem> itemListTemp = new List<FactItem>();

            string variable = Variable.Substring(Variable.IndexOf(':') + 1);

            FactVariable factVariable1 = GetFactVariable(Variable, variableSet);

            List<FactItem> factItems = variableSet.variableItems[Variable];

            if (factItems.Count == 0)
            {
                return itemListTemp;
            }

            FactVariable factVariable2 = GetFactVariableFromFilter(this.Label, variableSet);

            foreach (FactItem itemToFilter in itemsToFilter)
            {
                foreach (FactItem itemToCompare in factItems)
                {
                    if (variableSet.MatchUncoveredAspect(itemToCompare, itemToFilter, variableSet, factVariable1, factVariable2, factItems))
                    {
                        itemListTemp.Add(itemToFilter);
                    }
                }
            }

            return itemListTemp;
        }

    }
}
